const fs = require("fs");

const fileService = require("../service/file.service");
const { PICTURE_PATH, AVATAR_PATH } = require("../constans/file-path");
const userService = require("../service/user.service");
const { APP_HOST, APP_PORT } = require("../app/config");
const File = require("../model/file.model");
const { logger } = require("../../logger");

class FileController {
  async saveAvatarInfo(ctx, next) {
    // 1.获取图像相关的信息
    // TODO 这里的req是个啥？
    const { filename, mimetype, size } = ctx.req.file;
    const { id } = ctx.user;

    // 2.将图像信息数据保存到数据库中
    const result = await fileService.createAvatar(filename, mimetype, size, id);

    // 3.将图片地址保存到user表中
    const avatarUrl = `${APP_HOST}:${APP_PORT}/users/${id}/avatar`;
    await userService.updateAvatarUrlById(avatarUrl, id);

    // 4.返回结果
    ctx.body = {
      statusCode: 200,
      message: {
        msg: "上传头像成功",
      },
    };
  }

  async savePictureInfo(ctx, next) {
    const files = ctx.req.files;
    const { id } = ctx.user;
    for (let file of files) {
      const { originalname, filename, mimetype, size } = file;
      await File.create({ filename: originalname, mimetype, size, user_id: id })
        .then((res) => {
          ctx.success({ url: res.filename });
        })
        .catch((err) => {
          ctx.fail();
          logger.error(err);
        });
    }
  }

  // 上传视频
  async uploadVideo(ctx, next) {
    const file = ctx.request.files.file;
    if (file) {
      const reader = fs.createReadStream(file.path);
      const ext = file.name.split(".").pop();
      const dir = path.join(
        __dirname,
        `../../uploads/video/${new Date().getTime()}.${ext}`
      );
      const upStream = fs.createWriteStream(dir);
      reader.pipe(upStream);
      return (ctx.body = "success");
    } else {
      return (ctx.body = "error");
    }
  }
}

module.exports = new FileController();
